import router from '../router'
import axios from 'axios'
import store from '@/store/index.js'
import types from '@/constants/types'
import apiContext from '@/constants/apiContext' // 禁用加载loading弹窗api
import apiPermission from '@/constants/apiPermission'  //过滤掉不用token的api
import {
    transToLowerCase
} from '@/tools/helper.js' // 工具类方法

import {
    Loading,
    MessageBox,
    Message,
    Notification,
} from 'element-ui'; // 配置请求的默认值 iframe用?
window.PUBLICHOSTA = 'http://192.168.1.170:9200/';
window.OTHERPUBLICHOSTA = 'http://192.168.1.170:5222/';
window.PUBLICPYTHON = 'http://p1.chinazdap.com'; // python 在线运行请求地址
window.FILEIP = 'http://192.168.1.150:9992/api/v1/UploadFiles/PostFiles'; //文件上传ip
window.MUTLFILEIP = 'http://192.168.1.150:9992/api/v1/UploadFiles/PostCollectionFiles'; //文件批量上传


// axios 配置|中断请求
window.cancelArr = [];
axios.defaults.timeout = 100000;
axios.defaults.headers['Content-Type'] = 'application/json';
// axios.defaults.headers['Cache-Control'] = 'max-age=3000';
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? PUBLICHOSTA : PUBLICHOSTA;

// axios.defaults.transformRequest = [function(data) {
//     if (typeof data == 'object') {
//         return JSON.stringify(data)
//     } else if (typeof data == 'string' && data) {
//         return JSON.parse(data);
//     }
//     return data || {};
// }];

let loadingIns=null;
// 请求拦截
axios.interceptors.request.use(
    config => {
        // config 设置CancelToken
        let CancelToken = axios.CancelToken;
        let source = CancelToken.source();
        window.cancelArr.push(source);
        config.cancelToken = source.token;
        //config 设置accessToken
        if (sessionStorage.getItem('accessToken')) {
            config.headers.token = sessionStorage.getItem('accessToken')
        } else {
            let flag = false;
            for (let i = 0, len = apiPermission.length; i < len; i++) {
                let apiStr = apiPermission[i];
                if (config.url.indexOf(apiStr) > -1) {
                    flag = true;
                    break;
                }
            }
            if (!flag) source.cancel('无效的Token值！');
        }
        //禁用加载loading弹窗
        let isForbidLoading = false;
        for (let i = 0, len = apiContext.length; i < len; i++) {
            let apiStr = apiContext[i];
            if (config.url.indexOf(apiStr) > -1) {
                isForbidLoading = true;
                break;
            }
        }
        if (!isForbidLoading) {
            loadingIns = Loading.service({})
        }
        // 处理get post 的参数问题
        if (config.method == 'get' || config.method == 'delete') { // 拼接参数
            const paramsArray = [];
            Object.keys(config.data).forEach(key =>
                paramsArray.push(`${key}=${config.data[key]}`)
                )
            config.data = paramsArray.join('&');
            config.url = `${config.url}?${config.data}`
        }


        return config
    },
    err => {
        if (loadingIns)
            loadingIns.close()
        return Promise.reject(err)
    }
    );
// http response 拦截器
axios.interceptors.response.use(
    response => {
        if (loadingIns)
            loadingIns.close();
        let resData = response.data;
        if (resData) {

            let res = transToLowerCase(resData);
            // let res1 = transToUpperCase(res);
            let code = res.code;
            let entity = res;
            let message = res.msg || res.exceptionMessage;
            switch (code) {
                case -1:
                case 200:
                case 402:
                return Promise.resolve(entity)
                case 401:
                    //中断请求
                    sessionStorage.removeItem('loginflag'); //移除登录的标记
                    if (window.cancelArr && window.cancelArr.length) {
                        window.cancelArr.map(ct => {
                            ct.cancel('您已下线！');
                        });
                        window.cancelArr = [];
                    }
                    MessageBox(message, '提示', {
                        showClose: false,
                        confirmButtonText: '确定',
                    }).finally(() => {
                        sessionStorage.clear();
                        // sessionStorage.setItem('route', '/Home');
                        store.commit(`${types.LOGINOUT}`)
                        // window.location.href = "/";
                        // setTimeOut(() => {
                        //     store.commit(`${types.LOGINOUT}`)
                            // store.commit(`${types.LOGINOUT}`)
                            // store.commit(`${types.ISSHOWLOGIN}`, { boolean: true });
                        // }, 1000)
                    });
                    return Promise.reject(entity)
                case 500:
                    //中断请求
                    console.log(res)
                    sessionStorage.removeItem('loginflag'); //移除登录的标记
                    if (message && message.indexOf('"errcode":45009') >= 0) {

                    } else {
                        Notification.error({
                            title: "提示",
                            duration: 1000,
                            message: message || '系统异常，请稍候再试！',
                        });
                    }
                    return Promise.reject(entity)
                    default:
                    Notification.error({
                        title: "提示",
                        duration: 1000,
                        message: message || '系统异常，请稍候再试！',
                    });
                    return Promise.reject(entity)
                }
            } else {
                Notification.error({
                    title: "错误",
                    message: "错误码：" + res.StatusCode + " 错误信息：" + res.Message,
                });
            }
        },
        error => {
            console.log(error);
            if (loadingIns) loadingIns.close()
                let {
                    code,
                    message
                } = error;
            // if (code === 'ECONNABORTED' || message === 'Network Error') {
            //     MessageBox({
            //         title: '错误',
            //         message: `${code === 'ECONNABORTED' ? '请求超时' : '网络异常'}，请稍候再试！`,
            //         type: 'error'
            //     })
            // }
            if (code === 'ECONNABORTED' || message === 'Network Error') {
            //   Message({
            //     message: `${code === 'ECONNABORTED' ? '请求超时' : '网络异常'}，请稍候再试！`,
            //     type: 'warning',
            //     duration:800
            // });
                setTimeout(()=>{
                    router.push({
                        path: "/networkErr",
                    });
                },3000)
            }else{
                // setTimeout(()=>{
                //     router.push({
                //         path: "/networkErr",
                //     });
                // },3000)
            }
            return Promise.reject(error)
        }
    )

export default axios
